package com.zr.daoimpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.zr.dao.FunctionDao;
import com.zr.model.Function;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Repository(value="functionDao")
public class FunctionDaoImpl<T> extends BaseDaOImpl<T> implements FunctionDao<T>{

	@Override
	public JSONArray getFuncsByParentIdAndRole(int parentId, String funcs) {
		// TODO Auto-generated method stub
		JSONArray json = new JSONArray();
		
		String hql = "from Function f where f.parentid=:parentid and f.funcid in ("+funcs+")";
		Query   query  =this.getCurrentSession().createQuery(hql);
		query.setInteger("parentid",parentId );
		List<Function> functions = query.list();
		for (Function function : functions) {
			  JSONObject  func =  new JSONObject();
			  func.put("id", function.getFuncid());
			  func.put("text", function.getFuncname());
			  func.put("state", function.getFuncstate());
			  JSONObject  attr  = new JSONObject();
			  attr.put("fpath", function.getFuncpath());
			  func.put("attributes", attr);
			  json.add(func);
		}
	
		return json;
	}
	@Override
	public JSONArray getUserFuncsByParentId(int parentId, String funcs) {
		// TODO Auto-generated method stub
		
		JSONArray   userfuncs  = this.getFuncsByParentIdAndRole(parentId,funcs);
		for (int i = 0; i < userfuncs.size(); i++) {
			  String state = userfuncs.getJSONObject(i).getString("state");
			  if("open".equals(state)){
				     continue;
			  }else{
				   int currentId = userfuncs.getJSONObject(i).getInt("id");
				   JSONArray   children  =  this.getUserFuncsByParentId(currentId,funcs);
				   userfuncs.getJSONObject(i).put("children", children);
			  }
		}		
		return  userfuncs;
	}
}
